package com.cincc.taofangwang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.cincc.taofangwang.R;
import com.cincc.taofangwang.common.MyUtils;
import com.cincc.taofangwang.common.OkHttpUtils;
import com.cincc.taofangwang.common.SharePreferenceUtil;
import com.cincc.taofangwang.constant.AttrsConstant;
import com.cincc.taofangwang.constant.CallConstant;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "fengzi";
    TextView phoneTv;
    View phoneLine;

    TextView jobTv;
    View jobLine;

    ConstraintLayout phoneLayout;
    ConstraintLayout jobLayout;

    EditText editOne, editTwo, editThree, editOne1, editTwo1, editThree1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ImmersionBar.with(this).statusBarDarkFont(false).init();
        initView();
    }

    private void initView() {
        phoneTv = findViewById(R.id.title_phone_tv);
        phoneLine = findViewById(R.id.title_phone_line_view);

        jobTv = findViewById(R.id.title_job_number_tv);
        jobLine = findViewById(R.id.title_job_line_tv);

        phoneLayout = findViewById(R.id.phone_layout);
        jobLayout = findViewById(R.id.job_layout);

        editOne = findViewById(R.id.edit_one);
        editTwo = findViewById(R.id.edit_two);
        editThree = findViewById(R.id.edit_three);

        editOne1 = findViewById(R.id.edit_one1);
        editTwo1 = findViewById(R.id.edit_two1);
        editThree1 = findViewById(R.id.edit_three1);

        editOne.setText((String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.KEY1_PHONE, ""));
        editTwo.setText((String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.KEY2_PHONE, ""));
        editThree.setText((String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.KEY3_PHONE, ""));

        editOne1.setText((String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.KEY1_JOB, ""));
        editTwo1.setText((String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.KEY2_JOB, ""));
        editThree1.setText((String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.KEY3_JOB, ""));
    }

    public void onClick(View view) {
        if (view.getId() == R.id.phone_ll) {
            switchView(true);
        } else if (view.getId() == R.id.job_ll) {
            switchView(false);
        } else if (view.getId() == R.id.phone_login_relayout) {
            loginByPhone();
        } else if (view.getId() == R.id.job_login_relayout) {
            loginByJobNumber();
        }
    }

    private void switchView(boolean isPhone) {
        phoneLayout.setVisibility(isPhone ? View.VISIBLE : View.GONE);
        jobLayout.setVisibility(isPhone ? View.GONE : View.VISIBLE);
        phoneTv.setTextColor(isPhone ? getColor(R.color.primary_color) : getColor(R.color.black));
        phoneLine.setVisibility(isPhone ? View.VISIBLE : View.GONE);
        jobTv.setTextColor(isPhone ? getColor(R.color.black) : getColor(R.color.primary_color));
        jobLine.setVisibility(isPhone ? View.GONE : View.VISIBLE);
    }

    private void startMain(boolean isPhone) {
        if (isPhone) {
            SharePreferenceUtil.getInstance().setValue(AttrsConstant.KEY1_PHONE, oneValue);
            SharePreferenceUtil.getInstance().setValue(AttrsConstant.KEY2_PHONE, twoValue);
            SharePreferenceUtil.getInstance().setValue(AttrsConstant.KEY3_PHONE, threeValue);
        } else {
            SharePreferenceUtil.getInstance().setValue(AttrsConstant.KEY1_JOB, oneValue);
            SharePreferenceUtil.getInstance().setValue(AttrsConstant.KEY2_JOB, twoValue);
            SharePreferenceUtil.getInstance().setValue(AttrsConstant.KEY3_JOB, threeValue);
        }
        Intent i = new Intent(this, MainActivity.class);
        startActivity(i);
        finish();
    }

    private void loginByPhone() {
        try {
            oneValue = editOne.getText().toString();
            twoValue = editTwo.getText().toString();
            threeValue = editThree.getText().toString();
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("type", "in");
            c.put("vccId", twoValue);
            c.put("phoneNum", oneValue);
            c.put("password", MyUtils.md5(threeValue));
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);

            jsonObject.put("id", "Agent");
            jsonObject.put("act", "login");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", "");
            CallConstant.VCCID = twoValue;
            doRequest(jsonObject.toString(), true);
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    String oneValue = "";
    String twoValue = "";
    String threeValue = "";

    private void loginByJobNumber() {
        try {
            oneValue = editOne1.getText().toString();
            twoValue = editTwo1.getText().toString();
            threeValue = editThree1.getText().toString();
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("type", "in");
            c.put("vccId", oneValue);
            c.put("userId", twoValue);
            c.put("password", MyUtils.md5(threeValue));
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);

            jsonObject.put("id", "Agent");
            jsonObject.put("act", "login");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", "");
            CallConstant.VCCID = oneValue;
            doRequest(jsonObject.toString(), false);
        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void doRequest(String data, boolean isPhone) {
        Log.e(TAG, "doRequest: " + data);
        BasePopupView show = new XPopup.Builder(this).asLoading().show();
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject j = new JSONObject(data);
                    int code = j.getInt("response_code");
                    String msg = j.getString("response_msg");
                    if (code == 0) {
                        CallConstant.TOKEN = j.getJSONArray("data").getJSONObject(0).getString("token");
                        Log.e(TAG, "onSuccessful: token " + CallConstant.TOKEN);
                        runOnUiThread(() -> startMain(isPhone));
                    } else {
                        runOnUiThread(() -> Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    runOnUiThread(show::dismiss);
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                runOnUiThread(() -> {
                    Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    show.dismiss();
                });
            }
        });
    }
}
